package com.qiangrong.oa2k3cloud.common.task;

import com.alibaba.fastjson.JSONObject;
import com.qiangrong.oa2k3cloud.common.config.K3CloundConfig;
import com.qiangrong.oa2k3cloud.common.entity.FormtableMain30Entity;
import com.qiangrong.oa2k3cloud.common.enums.KDFormIdEnum;
import com.qiangrong.oa2k3cloud.common.enums.ResultEnum;
import com.qiangrong.oa2k3cloud.common.kingdee.service.KingdeeService;
import com.qiangrong.oa2k3cloud.common.repository.FormtableMain30Repository;
import com.qiangrong.oa2k3cloud.common.service.FormtableMain30Management;
import com.qiangrong.oa2k3cloud.common.utils.BaseUtil;
import com.qiangrong.oa2k3cloud.common.utils.file.FileUtil;
import com.qiangrong.oa2k3cloud.common.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @date 2019/1/4 15:07
 */
@Component
@Slf4j
public class TimerTask {

    @Autowired
    private KingdeeService kingdeeService;
    @Autowired
    private K3CloundConfig k3CloundConfig;
    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    private  FormtableMain30Management formtableMain30Management;
    @Autowired
    private FormtableMain30Repository formtableMain30Repository;


    private static  String template;
    private static final String POST_K3CloudUR = "";

    @Scheduled(fixedRate = 5000)
    public void login() throws IOException {
        //登录金蝶系统
        String loginParam = BaseUtil.buildLogin("573994707a5bb0","administrator","888888",2052);

        ResultVo login = kingdeeService.login(k3CloundConfig.getUrl()+k3CloundConfig.getLogin(),loginParam);

        if(!login.getCode().equals(ResultEnum.SUCCESS.getCode())){
            log.error("【登录金蝶系统失败】：{}",login.getMsg());
            return;
        }else {
            log.info("【登录金蝶系统成功】：{}",login.getMsg()+ResultEnum.SUCCESS.getCode());
        }
        Map<String,Object> map = (Map<String, Object>) login.getData();
        String cookie = map.get("cookie").toString();

        //读取核算单位与账簿对照表
        File file_fabood = resourceLoader.getResource(
                "classpath:templates/fabook.json").getFile();
        String template_fabook = FileUtil.loadFile(file_fabood);
        JSONObject fabook = BaseUtil.getFaBookId(template_fabook);
        //获取凭证数据模板
        File file_gl = resourceLoader.getResource(
                "classpath:templates/glvoucher.json").getFile();
        String template_gl = FileUtil.loadFile(file_gl);
        //查询差旅报销符合条件的记录
        List<Object> list = formtableMain30Management.findFormtableMain30List();
        if(!list.isEmpty()){
            for (Object chailv:list
                 ) {
                Object[] chailvlist = (Object[]) chailv;
                Map<String,Object> chailvmap= new HashMap<>();
                chailvmap.put("mid",chailvlist[0]);
                chailvmap.put("mrequestId",chailvlist[1]);
                chailvmap.put("mbianhao",chailvlist[2]);
                chailvmap.put("mbaoxiaoriqi",chailvlist[3]);
                chailvmap.put("mchucdidian",chailvlist[4]);
                chailvmap.put("msuixingrenyuan",chailvlist[5]);
                chailvmap.put("mdanjushu",chailvlist[6]);
                chailvmap.put("mchuchaishiyi",chailvlist[7]);
                chailvmap.put("mbaoxiaogongsi",chailvlist[8]);
                chailvmap.put("mbxgsjt",chailvlist[9]);
                chailvmap.put("iname",chailvlist[10]);
                chailvmap.put("mbaoxiaozjije",chailvlist[11]);
                String orgName = (String) chailvmap.get("iname");
                String fabookid = (String) fabook.get(orgName);
                String chuchaishiyi = (String) fabook.get("mchuchaishiyi");
                //构造凭证接口数据
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateNow = sdf.format(date);
                String glvoucher = BaseUtil.buildVoucher(template_gl, KDFormIdEnum.GL_VOUCHER.getFormid(),
                        "005",dateNow,"分录摘要","1002",5000.0,"1001",5000.0);
                //调用保存接口
                //log.info(glvoucher);
                ResultVo  glSave= kingdeeService.save(k3CloundConfig.getUrl()+k3CloundConfig.getSave(),cookie,glvoucher);
                if(!glSave.getCode().equals(ResultEnum.SUCCESS.getCode())){
                    log.error("【凭证保存出错】：{}",glSave.getMsg());
                    return;
                }else {
                    Map<String,Object> data = (Map<String, Object>) glSave.getData();
                    log.info("【凭证保存成功】：{}","生成凭证编号："+data.get("Number")+" ID:"+data.get("Id"));
                    //回写OA流程记录凭证号等信息
                    Integer mid = (Integer) chailvmap.get("mid");
                    if(mid >0){
                        Optional<FormtableMain30Entity> entity = formtableMain30Repository.findById(mid);
                        if(entity.isPresent()) {
                            entity.get().setBeizhu("生成凭证编号：" + data.get("Number") + " ID:" + data.get("Id"));
                            //formtableMain30Repository.save(entity.get());
                        }
                    }

                }

            }
        }


        /*File file = resourceLoader.getResource(
                "classpath:templates/material.json").getFile();
        //获取物料数据模板
        String template = FileUtil.loadFile(file);

        //构造物料接口数据
        String material = BaseUtil.buildMaterial(template, KDFormIdEnum.MATERIAL.getFormid(),"100108","A80柴油机","A80");
        //调用保存接口
        log.info("json"+material);
        ResultVo save = kingdeeService.save(k3CloundConfig.getUrl()+k3CloundConfig.getSave(),cookie,material);
        if(!save.getCode().equals(ResultEnum.SUCCESS.getCode())){
            log.error("【保存出错】：{}",save.getMsg());
            return;
        }

        //提交物料
        String submitParam = BaseUtil.buildParam(KDFormIdEnum.MATERIAL.getFormid(),"100108",null);
        ResultVo submit = kingdeeService.save(k3CloundConfig.getUrl()+k3CloundConfig.getSubmit(),cookie,submitParam);
        if(!submit.getCode().equals(ResultEnum.SUCCESS.getCode())){
            log.error("【提交出错】：{}",submit.getMsg());
            return;
        }

        //审核物料
        String auditParam = BaseUtil.buildParam(KDFormIdEnum.MATERIAL.getFormid(),"100108","true");
        ResultVo audit = kingdeeService.save(k3CloundConfig.getUrl()+k3CloundConfig.getAudit(),cookie,auditParam);
        if(!audit.getCode().equals(ResultEnum.SUCCESS.getCode())){
            log.error("【审核出错】：{}",audit.getMsg());
        }*/

    }
}
